// 基础配置
const getApiBase = () => {
  if (typeof window !== 'undefined') {
    return 'https://lease.wckj.tech/api/v1'
    // return 'http://localhost:3000/api/v1'
  } else {
    // return 'http://localhost:3000/api/v1'
    return 'https://lease.wckj.tech/api/v1'
  }
}

// 获取认证token (只在客户端)
const getToken = () => {
  if (typeof window !== 'undefined' && window.localStorage) {
    return localStorage.getItem('token')
  }
  return null
}

// 创建请求实例 (模拟 axios 的接口)
const createRequest = () => {
  const request = async (config) => {
    const { url, method = 'GET', data, params, headers = {}, ...otherConfig } = config
    
    // 构建完整 URL
    let fullUrl = url.startsWith('http') ? url : `${getApiBase()}${url}`
    
    // 处理查询参数
    if (params) {
      const searchParams = new URLSearchParams()
      Object.keys(params).forEach(key => {
        if (params[key] !== null && params[key] !== undefined) {
          searchParams.append(key, params[key])
        }
      })
      const queryString = searchParams.toString()
      if (queryString) {
        fullUrl += (fullUrl.includes('?') ? '&' : '?') + queryString
      }
    }
    
    // 准备请求配置
    const fetchConfig = {
      method: method.toUpperCase(),
      headers: {
        'Content-Type': 'application/json',
        ...headers
      },
      ...otherConfig
    }
    
    // 添加 token (只在客户端)
    if (typeof window !== 'undefined') {
      try {
        const token = getToken()
        if (token) {
          fetchConfig.headers.Authorization = `Bearer ${token}`
        }
      } catch (error) {
        console.warn('获取token失败:', error)
      }
    }
    
    // 处理请求体
    if (data) {
      if (data instanceof FormData) {
        // FormData 不需要设置 Content-Type，让浏览器自动设置
        delete fetchConfig.headers['Content-Type']
        fetchConfig.body = data
      } else if (typeof data === 'object') {
        fetchConfig.body = JSON.stringify(data)
      } else {
        fetchConfig.body = data
      }
    }
    
    try {
      // console.log('发送请求:', method.toUpperCase(), fullUrl, fetchConfig)
      
      const response = await fetch(fullUrl, fetchConfig)
      
      console.log('收到响应:', response.status, response.statusText)
      
      // 检查响应状态
      if (!response.ok) {
        const errorText = await response.text()
        let errorData
        try {
          errorData = JSON.parse(errorText)
        } catch {
          errorData = { message: errorText || `HTTP ${response.status}` }
        }
        
        const error = new Error(errorData.message || `请求失败 (${response.status})`)
        error.response = {
          status: response.status,
          statusText: response.statusText,
          data: errorData
        }
        throw error
      }
      
      // 解析响应
      const contentType = response.headers.get('content-type')
      let responseData
      
      if (contentType && contentType.includes('application/json')) {
        responseData = await response.json()
      } else {
        responseData = await response.text()
      }
      // console.log('响应数据:', responseData)
      
      // 返回数据 (模拟 axios 的 response.data)
      return responseData
      
    } catch (error) {
      console.error('API请求错误:', error)
      throw error
    }
  }
  
  // 创建一个可以直接调用的函数，同时有便捷方法
  const instance = request
  
  instance.get = (url, config = {}) => {
    return request({ url, method: 'GET', ...config })
  }
  
  instance.post = (url, data, config = {}) => {
    return request({ url, method: 'POST', data, ...config })
  }
  
  instance.put = (url, data, config = {}) => {
    return request({ url, method: 'PUT', data, ...config })
  }
  
  instance.delete = (url, config = {}) => {
    return request({ url, method: 'DELETE', ...config })
  }
  
  instance.patch = (url, data, config = {}) => {
    return request({ url, method: 'PATCH', data, ...config })
  }
  
  return instance
}

// 创建并导出默认实例
export const axiosInstance = createRequest()

// 文件上传函数
export const uploadFile = async (file, type = 'image') => {
  // 检查是否在客户端环境
  if (typeof window === 'undefined') {
    throw new Error('文件上传只能在客户端执行')
  }
  
  // 检查 FormData 是否可用
  if (typeof FormData === 'undefined') {
    throw new Error('当前环境不支持 FormData')
  }
  
  const formData = new FormData()
  formData.append('file', file)
  formData.append('type', type)
  
  try {
    const result = await axiosInstance.post('/upload', formData)
    return result
  } catch (error) {
    console.error('文件上传错误:', error)
    throw error
  }
}

// 创建自定义实例的工厂函数
export const createAxiosInstance = (config = {}) => {
  // 这里可以根据 config 创建自定义配置的请求实例
  return createRequest()
}

// 导出工具函数
export { getToken, getApiBase } 